package com.qf.service.impl;

import com.qf.entity.SysUser;
import com.qf.mapper.SysUserMapper;
import com.qf.service.SysUserService;
import com.qf.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ClassName: SysUserServiceImpl
 * @Author: WangHao
 * @Date: 2025/4/21 16:45
 * @Description:
 * @Version: 1.0
 */

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public String login(SysUser sysUser) {
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用MyUserDetailsService.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword()));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new RuntimeException("用户认证失败");
            } else {
                throw new RuntimeException(e.getMessage());
            }
        }

        // 认证成功，生成token
        // 生成jwt
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", authentication.getName());
        // 获取权限对象，用于提取权限数据
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        System.out.println("当前用户权限列表: " + authorities);
        Set<String> authoritySet = new HashSet<>();
        authorities.forEach(item -> authoritySet.add(item.getAuthority()));
        // 将权限数据放入claims,用于存入jwt
        claims.put("perms", authoritySet);
        return jwtUtils.createJwt(claims);
    }
}
